package com.xing.game.netty;

import com.xing.game.logic.HandlerManager;
import com.xing.game.logic.HandlerManagerImpl;
import com.xing.game.logic.login.LoginHandler;
import com.xing.game.logic.message.MessageConstants;
import com.xing.game.logic.player.Player;
import com.xing.game.server.BeanContext;
import com.xing.game.server.ExcutorWorkers;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageDispatcherWorker implements Worker{

    private static final Logger logger = LoggerFactory.getLogger(MessageDispatcherWorker.class);

    private Channel channel;

    private ExcutorWorkers gameWorker;

    private LoginHandler loginHandler;

    private HandlerManager handlerManager;

    public MessageDispatcherWorker(Channel channel)
    {
        this.channel = channel;

        gameWorker = BeanContext.getWorkers();

        loginHandler = (LoginHandler) BeanContext.getBean(LoginHandler.class);

        handlerManager = (HandlerManagerImpl)BeanContext.getBean(HandlerManagerImpl.class);
    }


    @Override
    public void onMessage(ChannelBuffer buffer) {

        final short msgId = (short)buffer.readUnsignedShort();
        short len = buffer.readShort();
        final byte[] data = new byte[len];
        if(len>0){
            buffer.readBytes(data);
        }
        try {
            Object attach = channel.getAttachment();

            if(msgId == MessageConstants.MSG_C2S_LOGIN){
                gameWorker.getGameExecutor(0).execute(new Runnable() {
                    @Override
                    public void run() {
                        loginHandler.login(channel, data);
                    }
                });
            }else if(attach instanceof Player){
                Player player = (Player) attach;
                gameWorker.getGameExecutor(player.getId()).execute(new Runnable() {
                    @Override
                    public void run() {
                        handlerManager.getHandler(msgId).dispater(msgId, channel, data);
                    }
                });
            }else{
                logger.error("attachment is not a Player");
                channel.close();
            }
        } catch (Throwable e) {
            e.printStackTrace();
            return;
        }
    }

    @Override
    public void onDisconnected() {

    }
}
